package com.ly.mpayment.rest.up.yiche;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.Config;
import com.ly.mpayment.core.util.DateUtils;
import com.ly.mpayment.core.util.HttpClient;
import com.ly.mpayment.core.util.StringUtils;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.net.URLDecoder;

/**
 * 易通达
 */
@Component
@Path("yiche")
public class YiTongDaRest {


    Logger logger = Logger.getLogger(YiTongDaRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;

    /**
     * { "orderId":"4028b8815e200012fxx",
     * "shopuuid":"4028b8815f6e3524015f6e3b61ef0004", "amount":"100",
     * "sign":"3183496d7f0cb397b819bdc89a11c0fc",
     * "productuuid":"4028b8815f7d4ae2015f86ee6aa70009", "phoneNum":"18000001111",
     * "notifyAddress":"http://ip:port/callmethod", "ts":"20170928115522" }
     *
     * @return
     */
//    public String commitOrder(String orderId, String amount, String productuuid, String phone, final String url, String sid, String notifyAddress, String key) {
//        String ts = new DateUtils().toTimeStamp();
////        md5(orderId=orderId&
////                shopuuid=shopuuid&
////                amount=amount&
////                phoneNum=phoneNum&
////                productuuid=productuuid&
////                notifyAddress=notifyAddress&
////                ts=ts&
////                key=key)
//        JSONObject data = new JSONObject();
//        data.put("orderId", orderId);
//        data.put("shopuuid", sid);
//        data.put("amount", amount);
//        data.put("pid", productuuid);
//        data.put("phone", phone);
//        data.put("notify", notifyAddress);
//        data.put("ts", ts);
//        data.put("sign", MD5.md5(StringSort.doSign(data).concat("&key="+key)));
//        return HttpClient.post(url, data.toString());
//    }


    private String getRechargeMd5(JSONObject json, UpShopInfo shop) {
        StringBuffer sb = null;
        sb = new StringBuffer();
        sb.append("oid=");
        sb.append(json.getString("oid"));
        sb.append("&sid=");
        sb.append(json.getString("sid"));
        sb.append("&pnum=");
        sb.append(json.getString("pnum"));
        sb.append("&pid=");
        sb.append(json.getString("pid"));
        sb.append("&ads=");
        sb.append(json.getString("ads"));
        sb.append("&ts=");
        sb.append(json.getString("ts"));
        sb.append("&key=");
        sb.append(shop.getUpkey());
        return MD5.md5(sb.toString());
    }

    private String getOrderStatuMd5Oid(JSONObject json, UpShopInfo shop) {
        StringBuffer sb = null;
        sb = new StringBuffer();
        sb.append("onum=");
        sb.append(json.getString("onum"));
        sb.append("&sid=");
        sb.append(json.getString("sid"));
        sb.append("&ts=");
        sb.append(json.getString("ts"));
        sb.append("&key=");
        sb.append(shop.getUpkey());
        return MD5.md5(sb.toString());
    }

    @SuppressWarnings("static-access")
    @Path("callBack")
    @POST
    public String callBack(String data) {

//        {"onum":"2c92860d7739e799017739ee58a20006","status":3,"amount":"1.00000","oid":"2c922ab77739edd6017739ee587c000a",
//        "pnum":"18782435842","ctime":1611584658,"sid":"2c92860d74532832017739ae6dcc0d8f",
//        "msg":"未找到供货商产品配置","sign":"c9f29b8e5c3888b4902ca67299ff0703"}

//        {"onum":"2c92860d773d14cb01773d398edb0037","status":3,"amount":"30.00000","oid":"2c922ab7773a28ae01773d398ec500ac"
//                ,"pnum":"13433377497","ctime":1611639918,"sid":"2c92860d74532832017739ae6dcc0d8f","sign":"31dc0e12fd7af65ec5c91b09afecad8a"}
        logger.info("yitongda_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            JSONObject jsonD = JSONObject.parseObject(data);
            UpOrder order = upOrderService.findById(jsonD.getString("oid"));
            if (order != null && jsonD.getString("status").equals("2") && order.getStatus() == Config.status[0]) {
                order.setRemark(jsonD.containsKey("msg") && !StringUtils.isBlank(jsonD.getString("msg")) ? URLDecoder.decode(jsonD.getString("msg")) : "");
                RechargeRest.successUpOrder.add(order);
                return  "0";
            } else if (order != null && order.getStatus() == Config.status[0] && jsonD.getString("status").equals("3")) {
                order.setRemark( jsonD.containsKey("msg") && !StringUtils.isBlank(jsonD.getString("msg")) ? URLDecoder.decode(jsonD.getString("msg")) : "");
                RechargeRest.failtUpOrder.add(order);
                return "0";
            } else {
                logger.info("yitongda_not_found_order:" + jsonD.getString("oid") + "," + (order == null ? "" : order.getUpphonenum()));
            }
        }
        return "0";
    }


    /**
     * 订单提交
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {
        UpOrder product = this.upOrderService.findOrderProduct(order.getUporderuuid());
        if (product != null) {

        }
        JSONObject data = new JSONObject();
        data.put("oid", order.getUporderuuid());
        data.put("sid", shop.getAppId());
        data.put("pid", order.getUpShopPro().getProductCode());
        data.put("pnum", order.getUpphonenum());
        data.put("ads", shop.getOrderCallAddress());
        data.put("ts", new DateUtils().toTimeStamp());
        data.put("sign", getRechargeMd5(data,shop));
        logger.info("commitOrder_yitongdaorder:"+order.getUporderuuid());
        //{"data":{"orderId":"2c92860d7739e799017739ee58a20006","time":"20210125222417"},"code":"00","message":"订单提交成功!"}
        String result = HttpClient.post(shop.getOrderCommitAddress(), data.toString());
        logger.info("commitOrder_yitongda:"+result+"data:"+data.toJSONString()+",ads:"+shop.getOrderCommitAddress());
        if (!StringUtils.isBlank(result)) {
            JSONObject json = JSONObject.parseObject(result);
            if (json.containsKey("code") && json.getString("code").equals("00")) {
                this.upOrderService.updateUpOrder(order, json.containsKey("data") ? json.getJSONObject("data").getString("orderId") : "");
            } else if(json.containsKey("code") &&
                    (json.getString("code").equals("20") || json.getString("code").equals("21")
                            || json.getString("code").equals("11")
                            || json.getString("code").equals("12")
                            || json.getString("code").equals("13")
                            || json.getString("code").equals("15")
                            || json.getString("code").equals("16")
                            || json.getString("code").equals("18")
                            || json.getString("code").equals("21")
                    )) {
                order.setRemark(json.containsKey("message") ? json.getString("message") : json.getString("msg"));
                RechargeRest.failtUpOrder.add(order);
            }else{
                this.upOrderService.updateUpOrderMsg(order,"",json.getString("msg"));
                logger.info("commitOrder_error:" + order.getUpphonenum());
            }
        } else {
            this.upOrderService.updateUpOrder(order, "");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    /**
     * 订单查询
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        String ts = new DateUtils().toTimeStamp();
        JSONObject data = new JSONObject();
        data.put("onum", upOrder.getUpOrderId());
        data.put("sid", shopInfo.getAppId());
        data.put("ts", ts);
        data.put("sign", getOrderStatuMd5Oid(data,shopInfo));

        String result =  HttpClient.post(shopInfo.getOrderStatusAddress(), data.toString());
        logger.info("yitongdaqueryOrder:"+upOrder.getUpphonenum()+":"+result+",data:"+data.toJSONString());
            //{"data":{"onum":"2c92860d773d14cb01773d398edb0037","ctime":"20210126135200","pnum":"13433377497",
        // "amount":30,"status":3,"pid":"2c92860d773d14cb01773d1b278d000d"},"code":"00","message":"查询成功"},
//        data:{"onum":"2c92860d773d14cb01773d398edb0037","sign":"3aa4822f4b2debf2fd7d952bf908c614","sid":"2c92860d74532832017739ae6dcc0d8f","ts":"20210126135200"}
        if (!StringUtils.isBlank(result)) {
            JSONObject jsonD = JSONObject.parseObject(result);
            if(jsonD.containsKey("data") && jsonD.getString("code").equals("00")){
                UpOrder order = upOrderService.findByUpOrderId(jsonD.getJSONObject("data").getString("onum"));
                if (order != null && jsonD.getJSONObject("data").getString("status").equals("2") && order.getStatus() == Config.status[0]) {
                    order.setRemark(jsonD.containsKey("msg") ? URLDecoder.decode(jsonD.getString("msg")) : "");
                    RechargeRest.successUpOrder.add(order);
                } else if (order != null && order.getStatus() == Config.status[0]
                        && jsonD.getJSONObject("data").getString("status").equals("3")) {
                    order.setRemark(URLDecoder.decode(jsonD.getString("msg")));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    logger.info("yitongda_not_found_order:" + jsonD.getJSONObject("data").getString("onum") + "," + order.getUpphonenum());
                }
            }else if(jsonD.getString("code").equals("1004")){
                //RechargeRest.failtUpOrder.put(upOrder.getUporderuuid(),jsonD.getString("message"));
                //flowService.orderHanlderFailt(upOrder, upOrderService, flowService, shopService, taskExecutor,jsonD.getString("message"));
            }else{
                logger.info("yitongda_not_found_order:" + jsonD.getJSONObject("data").getString("onum") + "," + upOrder.getUpphonenum());
            }
        }
    }
}
